package com.kfm.copy;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
/**
   使用 json 实现 深拷贝
       对象 <--> json
*/
public class DeepCopy {


    public static void main(String[] args) {
        Userinfo userinfo = new Userinfo();
        userinfo.setId(111);
        userinfo.setUsername("admin");
        userinfo.setPassword("123456");

        Top top = new Top();
        top.inner = new Inner();
        top.inner.num = 10;

        userinfo.setTop(top);

//        try {
//            Userinfo clone = (Userinfo) userinfo.clone();
//            System.out.println(userinfo);
//            System.out.println(clone);
//            System.out.println(userinfo.getTop().inner.num);
//            System.out.println(clone.getTop().inner.num);
//
//            userinfo.getTop().inner.num = 20;
//
//            System.out.println(userinfo.getTop().inner.num);
//            System.out.println(clone.getTop().inner.num);
//        } catch (CloneNotSupportedException e) {
//            e.printStackTrace();
//        }

        System.out.println(userinfo);
        /*
         * 对象  ---> json
         */
        // jackson
        JsonMapper jsonMapper = new JsonMapper();
        String string = null;
        try {
            string = jsonMapper.writeValueAsString(userinfo);
            System.out.println(string);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        /*
            json 字符串 ---> 对象
         */
        try {
            Userinfo userinfo1 = jsonMapper.readValue(string, Userinfo.class);
            System.out.println(userinfo1);

            System.out.println(userinfo.getTop().inner.num);
            System.out.println(userinfo1.getTop().inner.num);

            userinfo.getTop().inner.num = 20;

            System.out.println(userinfo.getTop().inner.num);
            System.out.println(userinfo1.getTop().inner.num);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


    }
}

@Data
class Userinfo implements Cloneable{
    private int id;

    private String username;

    private String password;

    private Top top;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}


class Top {
    public Inner inner;

    public void top(){
        System.out.println("top");
    }

}

class Inner{
    public int num;
}
